package com.ruoyi.shortplay.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.translate.LanguageCodes;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.play.domain.PlayOperaLog;
import com.ruoyi.play.mapper.PlayOperaLogMapper;
import com.ruoyi.setlanguages.io.ChannelInfo;
import com.ruoyi.setlanguages.service.YouTubeManager;
import com.ruoyi.shortplay.domain.MyChannelVideo;
import com.ruoyi.shortplay.domain.SupportedLanguagesIO;
import com.ruoyi.shortplay.domain.YoutobeDateOpera;
import com.ruoyi.shortplay.mapper.MyChannelVideoMapper;
import com.ruoyi.shortplay.mapper.YoutobeDateOperaMapper;
import com.ruoyi.shortplay.service.IMyChannelVideoService;
import com.ruoyi.translat.domain.TranslatSecret;
import com.ruoyi.translat.mapper.TranslatSecretMapper;
import com.ruoyi.until.CheckUtilsImp;
import com.ruoyi.youtobe.domain.VideoInfoVO;
import com.ruoyi.youtobe.domain.YoutobeChannelInfo;
import com.ruoyi.youtobe.mapper.YoutobeChannelInfoMapper;
import com.ruoyi.youtobe.service.impl.YoutubeVideoFetcher;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.tmt.v20180321.TmtClient;
import com.tencentcloudapi.tmt.v20180321.models.TextTranslateRequest;
import com.tencentcloudapi.tmt.v20180321.models.TextTranslateResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 我频道下的视频Service业务层处理
 *
 * @author ruoyi
 * @date 2025-11-18
 */
@Slf4j
@Service
public class MyChannelVideoServiceImpl implements IMyChannelVideoService {
    @Resource
    private MyChannelVideoMapper myChannelVideoMapper;

    /**
     * 查询我频道下的视频
     *
     * @param id 我频道下的视频主键
     * @return 我频道下的视频
     */
    @Override
    public MyChannelVideo selectMyChannelVideoById(Long id) {
        return myChannelVideoMapper.selectMyChannelVideoById(id);
    }

    /**
     * 查询我频道下的视频列表
     *
     * @param myChannelVideo 我频道下的视频
     * @return 我频道下的视频
     */
    @Override
    public List<MyChannelVideo> selectMyChannelVideoList(MyChannelVideo myChannelVideo) {
        return myChannelVideoMapper.selectMyChannelVideoList(myChannelVideo);
    }

    /**
     * 新增我频道下的视频
     *
     * @param myChannelVideo 我频道下的视频
     * @return 结果
     */
    @Override
    public int insertMyChannelVideo(MyChannelVideo myChannelVideo) {
        myChannelVideo.setCreateTime(DateUtils.getNowDate());
        if (myChannelVideo.getVideoUrl()!=null) {
            String videoId = myChannelVideo.getVideoUrl().replace("https://youtu.be/", "");
            myChannelVideo.setVideoId(videoId);
        }
        return myChannelVideoMapper.insertMyChannelVideo(myChannelVideo);
    }

    @Resource
    PlayOperaLogMapper playOperaLogMapper;
    @Resource
    YoutobeDateOperaMapper youtobeDateOperaMapper;

    /**
     * 修改我频道下的视频
     *
     * @param
     * @return 结果
     */
    @Override
    public AjaxResult updateMyChannelVideo(MyChannelVideo params) {
        if (StringUtils.isNotBlank(params.getVideoUrl())) {
            String videoId = params.getVideoUrl().replace("https://youtu.be/", "");
            params.setVideoId(videoId);
        }
        params.setUpdateTime(DateUtils.getNowDate());
        int i = myChannelVideoMapper.updateMyChannelVideo(params);
        return AjaxResult.success("修改成功！");
    }

    @Override
    public AjaxResult updateByYoutobeData(MyChannelVideo params) {
        MyChannelVideo video = myChannelVideoMapper.selectMyChannelVideoById(params.getId());
        if (video==null|| StringUtils.isBlank( video.getVideoId())) {
            return AjaxResult.error("数据不存在或视频链接为空，请确认数据后重试");
        }
        VideoInfoVO data = YoutubeVideoFetcher.getVideoDetailsByVideoId(video.getVideoId());
        if (data!=null) {
            video.setDefaultTitle(data.getDefaultTitle());
            video.setViewCount(data.getViewCount());
            video.setThumbnailUrl(data.getLocalUrl());
            video.setTitleKey(data.getTitleKey());
            video.setPublishTime(new Date(data.getPublishTime().getValue()));
            video.setState("release");
            myChannelVideoMapper.updateMyChannelVideo(video);
            //查看记录表是否有数据，有则修改，无则新增
            if (video.getOpId()!=null) {
                PlayOperaLog log = playOperaLogMapper.getPlayOperaLogByOpId(video.getOpId());
                //状态更新为 已发布时 片单剪辑发布表数据修改
                PlayOperaLog up = new PlayOperaLog();
                up.setId(log.getId());
                up.setOpId(video.getOpId());
                up.setPushDate(video.getPublishTime());
                up.setChannel(video.getChannelName());
                up.setVideoId(video.getVideoId());
                up.setRemark(video.getCopyRight());
                if (log != null) {
                    playOperaLogMapper.updatePlayOperaLogByOpId(up);
                } else {
                    //状态更新为 已发布时 片单剪辑发布表数据修改
                    YoutobeDateOpera opera = youtobeDateOperaMapper.selectYoutobeDateOperaById(video.getOpId());
                    if (opera != null) {
                        up.setPlay(opera.getTitle());
                        opera.setPushTitle(video.getDefaultTitle());
                        opera.setPushTime(video.getPublishTime());
                        youtobeDateOperaMapper.updateYoutobeDateOpera(opera);
                    }
                    playOperaLogMapper.insertPlayOperaLog(up);
                }
            }
        }
        return AjaxResult.success("更新成功！");
    }

    /**
     * 批量删除我频道下的视频
     * 
     * @param ids 需要删除的我频道下的视频主键
     * @return 结果
     */
    @Override
    public int deleteMyChannelVideoByIds(Long[] ids)
    {
        return myChannelVideoMapper.deleteMyChannelVideoByIds(ids);
    }

    /**
     * 删除我频道下的视频信息
     *
     * @param id 我频道下的视频主键
     * @return 结果
     */
    @Override
    public int deleteMyChannelVideoById(Long id) {
        return myChannelVideoMapper.deleteMyChannelVideoById(id);
    }

    @Resource
    private YouTubeManager youTubeManager;

    @Resource
    YoutobeChannelInfoMapper youtobeChannelInfoMapper;

    /**
     * @description: 添加多语言标题
     * @author: WYJ
     * @date: 2025/11/29
     * @param:
     */
    @Override
    public AjaxResult addSupportedLanguages(SupportedLanguagesIO params) {
        MyChannelVideo video = myChannelVideoMapper.selectMyChannelVideoById(params.getDataId());
        if (video == null) {
            return AjaxResult.error("数据不存在，请确认后重试！");
        }

        if (video.getChannelId() == null || StringUtils.isBlank(video.getVideoId())) {
            return AjaxResult.error("频道或者视频链接不可为空，请确认后重试！");
        }
        try {

            YoutobeChannelInfo channel = youtobeChannelInfoMapper.selectYoutobeChannelInfoById(video.getChannelId());
            if (channel == null || StringUtils.isBlank(channel.getChannelId())) {
                return AjaxResult.error("频道不存在或者频道id为空，请确认后重试！");
            }
            //查看我的频道 我的频道id与需要修改的频道id是否一致，否则，清除当前凭证，明天在做补充
            List<ChannelInfo> channels = youTubeManager.getMyChannels();
            if (CheckUtilsImp.listIsNotEmpty(channels)) {
                if (!channels.get(0).getId().equals(channel.getChannelId())) {
                    //清除凭证
                    youTubeManager.clearCredentialsOnly();
                    // 步骤2: 重新初始化服务（会触发新的OAuth流程）
                    boolean success = youTubeManager.forceReinitialize();
                    log.info("重新初始化服务 {}", success);
                    if (!success){
                        return AjaxResult.error("重启服务失败！");
                    }
                }
            }
            Map<String, String> languageTitles = setSupportedLanguages(params);
            youTubeManager.addMultiLanguageTitle(video.getVideoId(), languageTitles);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success("修改成功！");
    }

    private static final String ENDPOINT = "tmt.tencentcloudapi.com";
    private static final String REGION = "ap-shanghai";
    private static final Integer STR_LENGTH = 98;

    @Resource
    TranslatSecretMapper translatSecretMapper;

    // 获取支持的语言映射
    public Map<String, String> setSupportedLanguages(SupportedLanguagesIO params) {
        TmtClient translator = getTencentTranslator();
        Map<String, String> languages = new LinkedHashMap<>();
        String en = params.getEn();

        if (StringUtils.isNotBlank(params.getAr())) {
            languages.put("ar", getSubString(params.getAr()));
        } else {
            String ar = getTranslateStr(en, LanguageCodes.ARAB, "阿拉伯", translator);
            languages.put("ar", ar);
        }
        if (StringUtils.isNotBlank(params.getKm())) {
            languages.put("km",getSubString(params.getKm()));
        }
        if (StringUtils.isNotBlank(params.getFil())) {
            languages.put("fil", getSubString(params.getFil()));
        }
        if (StringUtils.isNotBlank(params.getEn())) {
            languages.put("en", getSubString(params.getEn()));
        }
        if (StringUtils.isNotBlank(params.getFr())) {
            languages.put("fr", getSubString(params.getFr()));
        } else {
            String fr = getTranslateStr(en, LanguageCodes.FRENCH, "法语", translator);
            languages.put("fr", fr);
        }
        if (StringUtils.isNotBlank(params.getMs())) {
            languages.put("ms", getSubString(params.getMs()));
        } else {
            String ms = getTranslateStr(en, LanguageCodes.MALAY, "马来语", translator);
            languages.put("ms", ms);

        }
        if (StringUtils.isNotBlank(params.getTa())) {
            languages.put("ta", getSubString(params.getTa()));
        }
        if (StringUtils.isNotBlank(params.getJa())) {
            languages.put("ja",  getSubString(params.getJa()));
        } else {
            String ja = getTranslateStr(en, LanguageCodes.JAPANESE, "日语", translator);
            languages.put("ja", ja);
        }
        if (StringUtils.isNotBlank(params.getKo())) {
            languages.put("ko",getSubString(params.getKo()) );
        } else {
            String ko = getTranslateStr(en, LanguageCodes.KOREAN, "韩语", translator);
            languages.put("ko", ko);
        }
        if (StringUtils.isNotBlank(params.getDe())) {
            languages.put("de", getSubString(params.getDe()));
        } else {
            String de = getTranslateStr(en, LanguageCodes.GERMAN, "德语", translator);
            languages.put("de", de);
        }
        if (StringUtils.isNotBlank(params.getTh())) {
            languages.put("th", getSubString(params.getTh()));
        } else {
            String th = getTranslateStr(en, LanguageCodes.THAILAND, "泰国语", translator);
            languages.put("th", th);
        }
        if (StringUtils.isNotBlank(params.getIt())) {
            languages.put("it", getSubString(params.getIt()));
        } else {
            String it = getTranslateStr(en, LanguageCodes.ITALIAN, "意大利", translator);
            languages.put("it", it);
        }
        if (StringUtils.isNotBlank(params.getEs())) {
            languages.put("es", getSubString(params.getEs()));
        } else {
            String es = getTranslateStr(en, LanguageCodes.SPANISH, "西班牙", translator);
            languages.put("es", es);
        }
        if (StringUtils.isNotBlank(params.getPt())) {
            languages.put("pt", getSubString(params.getPt()));
        } else {
            String pt = getTranslateStr(en, LanguageCodes.PORTUGUESE, "葡萄牙", translator);
            languages.put("pt", pt);
        }
        if (StringUtils.isNotBlank(params.getVi())) {
            languages.put("vi", getSubString(params.getVi()));
        } else {
            String vi = getTranslateStr(en, LanguageCodes.VIETNAM, "越南语", translator);
            languages.put("vi", vi);
        }
        if (StringUtils.isNotBlank(params.getMy())) {
            languages.put("my", getSubString(params.getMy()));
        }
        if (StringUtils.isNotBlank(params.getHi())) {
            languages.put("hi",getSubString(params.getHi()));
        } else {
            String hi = getTranslateYindi(en, LanguageCodes.HINDI, "印地语", translator);
            languages.put("hi", hi);
        }
        if (StringUtils.isNotBlank(params.getId())) {
            languages.put("id", getSubString(params.getId()));
        } else {
            String id = getTranslateStr(en, LanguageCodes.INDONESIA, "印度尼西亚语", translator);
            languages.put("id", id);
        }

        return languages;
    }


    @Override
    public AjaxResult titleTranslation(SupportedLanguagesIO params) {
        //获取翻译器：
        TmtClient translator = getTencentTranslator();
        Map<String, String> map = new LinkedHashMap<>(16);
        if (translator == null) {
            return null;
        }
        //高棉为空 菲律宾 泰米尔 缅甸为空
        String en = params.getEn();
        log.info("开始翻译{}", en);
        //翻译成中文
        String ch = "今天天气很好！";

        String ar = getTranslateStr(en, LanguageCodes.ARAB, "阿拉伯", translator);
        map.put("阿拉伯", ar);
        //高棉  km
        String km = translate(ch, LanguageCodes.CHINESECN, LanguageCodes.CAMBODIA, translator);
        map.put("高棉", km);
        //菲律宾 fil

        String fil = translate(ch, LanguageCodes.CHINESECN, LanguageCodes.PHILIPPINES, translator);
        map.put("菲律宾", fil);
        map.put("英语", en);
        String fr = getTranslateStr(en, LanguageCodes.FRENCH, "法语", translator);
        map.put("法语", fr);
        String ja = getTranslateStr(en, LanguageCodes.JAPANESE, "日语", translator);
        String ms = getTranslateStr(en, LanguageCodes.MALAY, "马来语", translator);
        map.put("马来语", ms);
        //泰米尔 ta
        String ta = getTranslateStr(en, LanguageCodes.THAMEL, "泰米尔", translator);
        map.put("泰米尔", ta);
        map.put("日语", ja);
        String ko = getTranslateStr(en, LanguageCodes.KOREAN, "韩语", translator);
        map.put("韩语", ko);
        String ge = getTranslateStr(en, LanguageCodes.GERMAN, "德语", translator);
        map.put("德语", ge);
        String it = getTranslateStr(en, LanguageCodes.ITALIAN, "意大利", translator);
        map.put("意大利", it);
        String th = getTranslateStr(en, LanguageCodes.THAILAND, "泰国语", translator);
        map.put("泰国语", th);
        String sp = getTranslateStr(en, LanguageCodes.SPANISH, "西班牙", translator);
        map.put("西班牙", sp);
        String po = getTranslateStr(en, LanguageCodes.PORTUGUESE, "葡萄牙", translator);
        map.put("葡萄牙", po);
        String vi = getTranslateStr(en, LanguageCodes.VIETNAM, "越南语", translator);
        map.put("越南语", vi);
        //缅甸 my
        String my = getTranslateStr(en, LanguageCodes.MYANMAR, "缅甸", translator);
        map.put("缅甸", my);
        String hi = getTranslateYindi(en, LanguageCodes.HINDI, "印地语", translator);
        map.put("印地语", hi);
        String id = getTranslateStr(en, LanguageCodes.INDONESIA, "印度尼西亚语", translator);
        map.put("印度尼西亚语", id);
        if (StringUtils.isNotBlank(en) && en.length() > STR_LENGTH) {
            map.put("英语", en.substring(0, STR_LENGTH));
        }
        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult titleTranslationTwo(SupportedLanguagesIO params) {
        Map<String, String> stringStringMap = setSupportedLanguages(params);
        return AjaxResult.success(stringStringMap);
    }

    private TmtClient getTencentTranslator() {
        //从数据库获取密钥
        TranslatSecret re = translatSecretMapper.selectTranslatSecretByType("Tencent");
        if (re == null || StringUtils.isBlank(re.getSecretId()) || StringUtils.isBlank(re.getSecretKey())) {
            return null;
        }
        log.info("TranslatSecret ", re);
        // 初始化认证对象
        Credential cred = new Credential(re.getSecretId(), re.getSecretKey());

        // 客户端配置
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint(ENDPOINT);

        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        return new TmtClient(cred, REGION, clientProfile);
    }

    String getTranslateStr(String title, String code, String desc, TmtClient client) {
        String re = "";
        try {
            Thread.sleep(100);
            re = translate(title, LanguageCodes.ENGLISH, code, client);
        } catch (Exception e) {
            e.printStackTrace();
        }
/*        if (re!=null) {
            log.info("中译 " + desc + ": " + re);
            log.info("中译 " + desc + "长度: " + re.length());
        }*/
        if (StringUtils.isNotBlank(re) && re.length() > STR_LENGTH) {
            re = re.substring(0, STR_LENGTH);
            log.info("截取后" + re);
        }
        return re;
    }

    String getSubString(String re) {
        if (StringUtils.isNotBlank(re) && re.length() > STR_LENGTH) {
            re = re.substring(0, STR_LENGTH);
            log.info("截取后" + re);
        }
        return re;
    }

    /**
     * 文本翻译
     *
     * @param sourceText 源文本
     * @param sourceLang 源语言，如：zh
     * @param targetLang 目标语言，如：en
     * @return 翻译结果
     */
    public String translate(String sourceText, String sourceLang, String targetLang, TmtClient client) {
        try {
            TextTranslateRequest req = new TextTranslateRequest();
            req.setSourceText(sourceText);
            req.setSource(sourceLang);
            req.setTarget(targetLang);
            req.setProjectId(0L); // 项目ID，0表示默认项目

            TextTranslateResponse resp = client.TextTranslate(req);
            String targetText = resp.getTargetText();
            return targetText;

        } catch (TencentCloudSDKException e) {
            System.err.println("翻译失败: " + e.getMessage());
            return null;
        }
    }

    String getTranslateYindi(String title, String code, String desc, TmtClient client) {
        String re = "";
        try {
            //Thread.sleep(30);
            String en = translate(title, LanguageCodes.CHINESE, LanguageCodes.ENGLISH, client);
            re = translate(en, LanguageCodes.ENGLISH, code, client);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.isNotBlank(re)) {
            log.info("中译 " + desc + ": " + re);
            log.info("中译 " + desc + "长度: " + re.length());
        }

        if (StringUtils.isNotBlank(re) && re.length() > STR_LENGTH) {
            re = re.substring(0, STR_LENGTH);
            log.info("截取后" + re);
        }
        return re;
    }
}
